/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.reports;

//Java
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.swing.JFrame;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.render.awt.AWTRenderer;
import org.apache.fop.viewer.PreviewDialog;
import org.apache.fop.viewer.SecureResourceBundle;
import org.apache.fop.viewer.Translator;
import org.apache.fop.viewer.UserMessage;

import br.ufmg.dees.insane.model.Model;

/**
 * This class is an AWT Viewer which shows model information.
 */
public class ModelAWTViewer {
	
    public static final String TRANSLATION_PATH = "/org/apache/fop/viewer/resources/";
	private Model model;
	private String drawingFile;
	
//********************************************************************************
	
	/** Constructor.
	*@param drawingFile The complete path to the file containig the drawing.
	*/
	public ModelAWTViewer(String drawingFile){
		this.drawingFile = drawingFile;
	}
	
//********************************************************************************
	
	public void setModel(Model model) {
		this.model = model;
	}
	
//********************************************************************************
	
	public Model getModel() {
		return model;
	}
	
//********************************************************************************
	
    protected PreviewDialog createPreviewDialog( AWTRenderer renderer, Translator res) throws FOPException, FileNotFoundException {
        
		PreviewDialog frame = new PreviewDialog(renderer, res);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		frame.setSize(new Dimension(800, 640));
		frame.validate();
        
		frame.setTitle("INSANE Relatory");
		Image ico = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("br/ufmg/dees/insane/images/Insane64.gif"));
        frame.setIconImage(ico);
		
        // center window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height)
            frameSize.height = screenSize.height;
        if (frameSize.width > screenSize.width)
            frameSize.width = screenSize.width;
        frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
        return frame;
    }
	
//********************************************************************************
	
    private SecureResourceBundle getResourceBundle(String path) throws IOException {
        URL url = getClass().getResource(path);
        if (url == null) {
            // if the given resource file not found, the english resource uses as default
            path = path.substring(0, path.lastIndexOf(".")) + ".en";
            url = getClass().getResource(path);
        }
        return new SecureResourceBundle(url.openStream());
    }
	
//********************************************************************************
	
    public void viewModel() throws IOException, FOPException, TransformerException {
		
		InputStream xsltfile = this.getClass().getResourceAsStream("/modelToFO.xsl");
		
        //Setup l18n
        String language = System.getProperty("user.language");
        Translator translator = getResourceBundle(TRANSLATION_PATH + "resources." + language);
        translator.setMissingEmphasized(false);
		
        UserMessage.setTranslator(getResourceBundle(TRANSLATION_PATH + "messages." + language));
		
        //Setup renderer
        AWTRenderer renderer = new AWTRenderer(translator);
		
        //Create preview dialog (target for the AWTRenderer)
		PreviewDialog frame = createPreviewDialog(renderer, translator);
		renderer.setProgressListener(frame);
        renderer.setComponent(frame);
		
        //Setup Driver
        Driver driver = new Driver();
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_ERROR);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);
		driver.setRenderer(renderer);
		
        try {
            // build FO tree: time
            frame.progress(translator.getString("Build FO tree") + " ...");
			
            TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
			Source src = this.getSourceForModel();
			Result res = new SAXResult(driver.getContentHandler());
			transformer.transform(src, res);
			
            //Show page
            frame.progress(translator.getString("Show"));
            frame.showPage();
			
        } catch (Exception e) {
            frame.reportException(e);
            if (e instanceof FOPException) {
                throw (FOPException)e;
            }
            throw new FOPException(e);
        }
    }
	
//********************************************************************************
	
	/**
     * Resturns a Source object for this object so it can be used as input for
     * a JAXP transformation.
     * @return Source The Source object
     */
    public Source getSourceForModel() {
        return new SAXSource(new ModelXMLReader(drawingFile),
                new ModelInputSource(model));
    }
	
//********************************************************************************
}
